package com.zyf.system.controller;

/**
 * @author 张云帆
 * 2025/3/25 11:42
 */

import com.google.gson.Gson;
import com.zyf.system.entity.ParamError;
import com.zyf.system.until.IpUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Log4j2
@Controller
public class BaseController {

    @Autowired
    private Gson gson;

    protected Map<String, Object> createResponse(String code, String msg, Object data){
        log.info("返回信息 code="+code+",msg="+msg);
        Map<String, Object > response = new HashMap<>();
        response.put("code", code);
        response.put("msg", msg);
        response.put("data", data);
        return response;
    }

    protected Map<String, Object> createResponseEtLog(String code, String msg, Object data){
        Map<String, Object > response = new HashMap<>();
        response.put("code", code);
        response.put("msg", msg);
        if(data!=null){
            response.put("data", data);
        }
        return response;
    }

    protected String getErrorMessage(List<ParamError> paramErrorList){
        StringBuilder stringBuilder = new StringBuilder();
        for(ParamError error:paramErrorList){
            stringBuilder.append(error.getDefaultMessage());
            stringBuilder.append(" ");
        }
        return stringBuilder.toString();
    }

    protected String getErrorMessage(BindingResult bindingResult){
        StringBuilder errors = new StringBuilder();
        List<ObjectError> list = bindingResult.getAllErrors();
        for(ObjectError error:list){
            errors.append(error.getDefaultMessage()).append(" ");
        }
        return errors.toString();
    }

    protected String httpLog(HttpServletRequest request){
        return "ip:"+ IpUtil.getIpAddr(request)+" url:"+request.getRequestURI()+" param:"+gson.toJson(request.getParameterMap());
    }
}

